# 截图宝 - 位移选取对话框
# 作者： 魏新崇
# 邮箱： weixinchong [at] 163.com
# 项目主页：https://gitee.com/weixinchong/auto-igrab

import sys, pyautogui, time
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QLabel, QPushButton, QSizePolicy

class DisplacementDialog(QWidget):

    def __init__(self, sc_left, sc_right, mouse_x0, mouse_y0, parent = None):
        super(DisplacementDialog, self).__init__(parent)
        # 初始化位移
        self.y = 0

        # 记录鼠标单击位置
        self.mouse_x0 = mouse_x0
        self.mouse_y0 = mouse_y0

        # 设定窗口状态
        self.setWindowFlags(Qt.FramelessWindowHint)
        self.setWindowOpacity(0.7)

        # 设定窗口尺寸及位置
        desktop = QApplication.desktop()
        self.height = desktop.screenGeometry().height() - 150
        self.setGeometry(sc_right + 150, 75, 50, self.height)
        self.setFixedHeight(self.height)
        self.setFixedWidth(130)
        
        # 设定布局
        layout = QVBoxLayout()
        self.setLayout(layout)
        # 添加控件
        # 1.状态栏
        self.label_state = QLabel('当前位移：0')
        self.label_state.setFixedHeight(20)
        layout.addWidget(self.label_state)
        # 2.定位符号
        area_pos = QLabel('●')
        area_pos.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.MinimumExpanding)
        area_pos.setAlignment(Qt.AlignCenter)
        area_pos.setCursor(Qt.CrossCursor)
        layout.addWidget(area_pos)
        # 3.确定位移按钮
        btn_finish = QPushButton('确定当前位移')
        btn_finish.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Fixed)
        btn_finish.setFixedHeight(20)
        btn_finish.clicked.connect(self.finish)
        layout.addWidget(btn_finish)

    def setValueObj(self, o1):
        self.o1 = o1

    def mouseReleaseEvent(self, event):
        '''鼠标按下后松开时确定位移'''
        # 确定本次位移
        x1_abs, y1_abs = pyautogui.position()
        y1 = y1_abs - (self.height / 2 + 75)  #获得相对于原点的坐标
        # 根据位移拖动文档
        pyautogui.mouseDown(x = self.mouse_x0, y = self.mouse_y0, button = 'left')  #按下鼠标
        pyautogui.dragTo(x = self.mouse_x0, y = self.mouse_y0 - y1, duration = 0.2, button = 'left')  #鼠标拖拽
        pyautogui.mouseUp(x = self.mouse_x0, y = self.mouse_y0 - y1, button = 'left')  #松开鼠标
        pyautogui.moveTo(x1_abs, y1_abs)  #鼠标返回
        # 计算总位移
        self.y = int(self.y + y1)
        self.label_state.setText('当前位移：%d' % self.y)

    def finish(self):
        self.o1.setValue(self.y)
        self.close()